<template>
  <a-form-model :model="form" ref="ruleForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" >
    <div class="formBox">
      <a-alert class="formalert" v-if="showAlert"  :message="message" type="warning" show-icon />
      <div class="formRow" :class="{inline:isInline}" v-for="(item,index) in formInfos" :key="index" :style="{width:item.width+'px'}"> 
        <!-- 标准控件 -->
        <!-- input -->
        <a-form-model-item v-if="item.type=='input'" :label="item.label" :prop="item.name">
          <a-input v-model="form[item.name]" :disabled ="item.isDisabled" :placeholder="item.placeholder"/>
        </a-form-model-item>
        <!-- 带搜索input -->
        <a-form-model-item v-if="item.type=='inputsearch'" :label="item.label" :prop="item.name">
          <a-input-search v-model="form[item.name]" :disabled ="item.isDisabled" :placeholder="item.placeholder" enter-button @search="inputOnSearch" />
          <!-- <a-input v-model="form[item.name]" :disabled ="item.isDisabled" :placeholder="item.placeholder"/> -->
        </a-form-model-item>
        <!-- 带按钮的input -->
        <a-form-model-item v-if="item.type=='inputbtn'" :label="item.label" :prop="item.name">
          <a-input-search :placeholder="item.placeholder"  @search="inputbtnOnSearch">
            <a-button slot="enterButton">
              {{item.btnname}}
            </a-button>
          </a-input-search>
        </a-form-model-item>
        <!-- number -->
        <a-form-model-item v-if="item.type=='number'" :label="item.label" :prop="item.name">
          <a-input v-model="form[item.name]" :type='item.type' :disabled ="item.isDisabled"  :placeholder="item.placeholder"/>
        </a-form-model-item>
        <!-- textarea -->
        <a-form-model-item v-if="item.type=='textarea'" :label="item.label"   :prop="item.name">
            <a-input  v-model="form[item.name]" type="textarea" :placeholder="item.placeholder"/>
        </a-form-model-item>
        <!-- select -->
        <a-form-model-item  v-if="item.type=='select'" :label="item.label"  :prop="item.name" >
          <a-select v-model="form[item.name]"  :placeholder="item.placeholder" @change="onSelectChange($event,item.link)" >
            <a-select-option v-for="(opt,ind) in item.options" :key="ind" :value="opt.id">
              {{opt.value}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- radio -->
        <a-form-model-item  v-if="item.type=='radio'" :label="item.label" :prop="item.name">
            <a-radio-group v-model="form[item.name]"  @change="radioOnChange($event,item.name)">
                <a-radio-button v-for="(opt,ind) in item.options" :key="ind" :value="opt.id">
                    {{opt.value}}
                </a-radio-button>
            </a-radio-group> 
        </a-form-model-item>
        <!-- radio2 -->
        <a-form-model-item  v-if="item.type=='radio2'" :label="item.label" :prop="item.name">
            <a-radio-group v-model="form[item.name]" >
                <a-radio v-for="(opt,ind) in item.options" :key="ind" :value="opt.id">
                    {{opt.value}}
                </a-radio>
            </a-radio-group> 
        </a-form-model-item>
        <!-- datatime -->
        <a-form-model-item  v-if="item.type=='datatime'" :label="item.label" :prop="item.name">
          <a-date-picker 
            v-model="form[item.name]"
            @change="(date,dateString)=>dateOnChange(date,dateString,item.name)" />
        </a-form-model-item>
        <!-- datarange -->
        <a-form-model-item  v-if="item.type=='datarange'" :label="item.label"  :prop="item.name"  >
          <a-range-picker
            v-model="form[item.name]"
            :ranges="{}"
            @change="(dates,dateStrings)=>datarangeOnChange(dates,dateStrings,item.name)"
          />
        </a-form-model-item>
        <!-- 复合控件 -->
        <!-- datatimeR -->
        <a-row v-if="item.type=='datatimeR'">
          <a-col :span="labelCol.span"><div class="labels">{{item.label[0]}} <span style="margin: 0 8px 0 2px">:</span> </div></a-col>
          <a-col :span="wrapperCol.span">
           <a-row>
              <a-col :span="8">
              <a-form-model-item   :prop="item.name[0]" :label-col="{ span: 0}" :wrapper-col="{ span: 24}" >
                <a-date-picker 
                  v-model="form[item.name[0]]"
                  :disabled-date="disabledAfterDate"
                  @change="(date,dateString)=>dateOnChange(date,dateString,item.name[0])" />
              </a-form-model-item>
            </a-col>
            <a-col :span="16">
              <a-form-model-item :label="item.label[1]"   :prop="item.name[1]" :label-col="{ span: 4}" :wrapper-col="{ span: 20}" >
                <a-date-picker
                  :disabled ="isDisabled"
                  v-model="form[item.name[1]]"
                  :disabled-date="disabledBeforeDate"
                  @change="(date,dateString)=>dateOnChange(date,dateString,item.name[1])" />
                <a-checkbox style="marginLeft:5px" @change="onChangeLong($event,item.name[1])">
                  长期
                </a-checkbox>
              </a-form-model-item>
            </a-col>
           </a-row>
          </a-col>
        </a-row>
        <!-- uploadimg -->
        <a-form-model-item  v-if="item.type=='uploadimg'" :label="item.label"  :prop="item.name" >
          <ImgUpload  
            v-model="form[item.name]"
            @change="imgUploaded($event,item.name)">
          </ImgUpload>
        </a-form-model-item>
        <!-- uploadimg -->
        <a-form-model-item  v-if="item.type=='uploadimgs'" :label="item.label"  :prop="item.name" >
          <ImgsUpload  
            v-model="form[item.name]"
            @change="imgsUploaded($event,item.name)">
          </ImgsUpload>
        </a-form-model-item>
        <!-- 字典选择 -->
        <a-form-model-item  v-if="item.type=='dicselect'"   :label="item.label"  :prop="item.name" >
          <DictSelect
            :dictCategory="item.dicName"
            :showCode="item.showCode"
            :disabled ="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="dicSelectChange($event,item.name)"
            :value="form[item.name]" >
          </DictSelect>
        </a-form-model-item>
        <!-- 单位选择组件 -->
        <a-form-model-item v-if="item.type==='orgselect'" :label="item.label"  :prop="item.name" >
          <OrgSelect
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="orgChange($event,item.name)"
            :value="form[item.name]">
          </OrgSelect>
        </a-form-model-item>
        <!-- 单位搜索组件 -->
        <a-form-model-item v-if="item.type==='orgsearch'" :label="item.label"  :prop="item.name" >
          <OrgSearch
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            @search="orgOnsearch($event,item.name)"
            :value="form[item.name]">
          </OrgSearch>
        </a-form-model-item>
        <!-- 业务控件 -->
        <!-- 注册证号Pid -->
        <a-form-model-item  v-if="item.type=='zchselect'" :label="item.label"  :prop="item.name" >
          <regisLicenseSelect
            :value="form[item.name]"
            :zhuangTai="item.zhuangTai"
            @change="regisLicenseChange($event,item.name)"
            >
          </regisLicenseSelect>
        </a-form-model-item>
        <!-- 供应商select选择组件 -->
        <a-form-model-item  v-if="item.type=='supplier'" :label="item.label"  :prop="item.name" >
          <SupplierSelect
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            :value="form[item.name]"
            @change="customerChange($event,item.name)"
            >
          </SupplierSelect>
        </a-form-model-item>
        <!-- 客户select选择组件 -->
        <a-form-model-item  v-if="item.type=='customer'" :label="item.label"  :prop="item.name" >
          <CustomerSelect
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            :value="form[item.name]"
            @change="customerChange($event,item.name)"
            >
          </CustomerSelect>
        </a-form-model-item>
        <!-- 结算单Select组件 -->
        <a-form-model-item v-if="item.type==='settlementSelect'" :label="item.label"  :prop="item.name" >
          <settlementSelect
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="onSelect(arguments,item.name)"
            :value="form[item.name]">
          </settlementSelect>
        </a-form-model-item>
        <!-- 配送地址Select组件 -->
        <a-form-model-item v-if="item.type==='deliveryAddressSelect'" :label="item.label"  :prop="item.name" >
          <deliveryAddressSelect
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="onSelect(arguments,item.name)"
            :value="form[item.name]">
          </deliveryAddressSelect>
        </a-form-model-item>
        <!-- 发票抬头Select组件 -->
        <a-form-model-item v-if="item.type==='invoiceInfoSelect'" :label="item.label"  :prop="item.name" >
          <invoiceInfoSelect
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="onSelect(arguments,item.name)"
            :value="form[item.name]">
          </invoiceInfoSelect>
        </a-form-model-item>
        <!-- 销售产品 -->
        <a-form-model-item  v-if="item.type=='salegoods'" :label="item.label"  :prop="item.name" >
          <SaleGoodsSelect
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            :value="form[item.name]"
            @change="salegoodsChange($event,item.name)"
            >
          </SaleGoodsSelect>
        </a-form-model-item>
        <!-- 三级联动选择器 -->
        <a-form-model-item  v-if="item.type=='threeLevelSelect'" :label="item.label"  :prop="item.name[0]" >
          <three-level-select
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            :value="[form[item.name[0]],form[item.name[1]],form[item.name[2]]]"
          >
          </three-level-select>
        </a-form-model-item>
        <!-- 表单中按钮 -->
        <a-form-model-item  v-if="item.type=='bottons'" :label-col="{ span: 0}" :wrapper-col="{ span: 24}" >
          <a-button class="btnInForm" type="primary"  @click="addInfo()">
            {{item.label[0]}}
          </a-button>
        </a-form-model-item>
      </div> 
      <slot></slot>
    </div>
    <div class="formBtn" :style="btnCusStyle" v-if="isBtn">
        <a-button class="btn" v-if="buttonText[2]" type="primary"  @click="cancel()">
          {{buttonText[2]}}
        </a-button>
        <a-button class="btn" v-if="buttonText[0]" type="primary"  @click="submitForm('ruleForm')">
          {{buttonText[0]}}
        </a-button>
        <a-button class="btn" v-if="buttonText[1]" type="primary"    @click="resetForm('ruleForm')">
          {{buttonText[1]}}
        </a-button>
    </div>
  </a-form-model>
</template>

<script>
import moment from 'moment'
import DictSelect from '@/views/sys/modules/DictSelect'
import ImgUpload from './upload/ImgUpload'
import ImgsUpload from './upload/ImgsUpload.vue'
import regisLicenseSelect from '@/views/app/biz/regisLicense/regisLicenseSelect'
import SaleGoodsSelect from '@/views/app/biz/salesGoods/SaleGoodsSelect'
import CustomerSelect from '@/views/app/biz/customer/CustomerSelect'
import SupplierSelect from '@/views/app/biz/supplier/SupplierSelect' 
import settlementSelect from '@/views/app/biz/settlement/settlementSelect' 
import deliveryAddressSelect from '@/views/app/biz/deliveryAddress/deliveryAddressSelect' 
import invoiceInfoSelect from '@/views/app/biz/invoiceInfo/invoiceInfoSelect' 
import OrgSelect from '@/views/sys/modules/OrgSelect'
import OrgSearch from '@/views/sys/modules/OrgSearch'
import threeLevelSelect from '@/views/app/biz/common/threeLevelSelect'
export default {
  components:{
    DictSelect,
    regisLicenseSelect,
    SaleGoodsSelect,
    CustomerSelect,
    SupplierSelect,
    ImgUpload,
    ImgsUpload,
    OrgSelect,
    OrgSearch,
    threeLevelSelect,
    deliveryAddressSelect,
    invoiceInfoSelect,
    settlementSelect
  },
  props:{
    showAlert: {
      default: false,
      require: false,
      type: Boolean
    },
    isInline:{
      type:Boolean,
      default:false
    },
    isBtn: {
      default: true,
      type: Boolean
    },
    message: {
      default: '',
      require: false,
      type: String
    },
    // 表单
    formInfos:{
      type:Array,
    },
    // 数据实体
    formDatas:{
      type:Object
    },
    // 表单规则集
    rules:{
      type:Object
    },
    btnCusStyle:{
      type:Object,
      default:()=>{
        return {
          boxShadow:'0 0 7px #bbb'
        }
      }
    },
    buttonText:{
      type:Array,
      default:()=>{
        return ['提交','放弃',""]
      }
    }
  },
  data(){
    return{  //:awrapperCol="awrapperCol" 
      labelCol: { span:8 },
      wrapperCol:{ span:12 },
      alabelCol:{ span:4 },
      awrapperCol:{span:16},
      form: JSON.parse(JSON.stringify(this.formDatas)),
      forms:{},
      isDisabled:false,
      before100years:null,
      resetobj:JSON.parse(JSON.stringify(this.formDatas))
    }
  },
  computed:{
    // getClassArr(){
    //   return (name)=>{
    //     let arr=[]
    //     for (const item of name) {
    //       if(this.form[item]){
    //         arr.push(this.form[item])
    //       }else{
    //         arr.push(null)
    //       }
    //     }
    //     return arr
    //   }
    // }
  },
  watch:{
    formDatas:{//深度监听，可监听到对象、数组的变化
        handler(val, oldVal){
          console.log("监听formDatas1",this.form, this.formDatas);
          this.form={...val}
          // this.form = Object.assign(this.form, val)
          //  this.resetobj=JSON.parse(JSON.stringify(val))
        },
        deep:true //true 深度监听
    }
  },
  mounted(){
    // this.resetobj = JSON.parse(JSON.stringify(this.formDatas))
  },
  methods:{
    //禁止选择今天之前的日期
    disabledBeforeDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day');
    },
    //禁止选择今天之后的日期
    disabledAfterDate(current) {
      // Can not select days before today and today
      return current && current > moment().endOf('day');
    },
    // 业务组件regisLicense change
    regisLicenseChange(val,name){
      this.form[name]=val
      this.$emit("onChangeType",name,val)
      //  this.$emit('onFind',this.form)
    },
    // 业务组件dicSelect change
    dicSelectChange(val,name){
      this.form[name]=val
      this.$emit("onChangeType",name,val)
      console.log('字典select',val);
    },
    inputOnSearch (val,name) {
      this.form[name]=val
      this.$emit("inputOnSearch",name,val)
    },
    inputbtnOnSearch (val,name) {
      this.form[name]=val
      this.$emit("onChangeType",name,val)
    },
    // 时间变化
    dateOnChange(date,dateString,name) {
      this.form[name] = dateString
      this.$emit("onChangeType",name,dateString)
      console.log(this.forms[name]);
    },
    datarangeOnChange(dates,dateStrings,name){
      //  this.form[name] = dateStrings
      this.form[name] = dateStrings
      this.$emit("onChangeType",name,val)
    },
    // 时间止（包含长期）
    onChangeLong(e,name){
      console.log(e.target.checked);
      let isChecked=e.target.checked
      if(isChecked){
        this.isDisabled=true;
        this.form[name]=moment().add(100, 'Y');
        this.forms[name] = this.form[name].format('YYYY-MM-DD');
      }else{
        this.isDisabled=false;
        this.form[name]=null; 
      }
      this.$emit("onChangeType", name, this.forms[name])
    },
    // selectChange
    onSelectChange(val,link){
      if(link=='1'){//通过val查询二级select
        let link2Item=this.formInfos.find(item=>{//查询第一个二级select,如需查询多个或三级select,在此修改
          return item.link=='2'
        })
        if(link2Item){
          this.form[link2Item.name]=undefined
          link2Item.options=[{id:'0',value:'所有'},{id:'1',value:'A市'},{id:'2',value:'B市'}]
          console.log(link2Item);
        }
        // this.$emit("onChangeType", name, this.forms[name])
      }
    },
    radioOnChange(val,name){//切换时如果表单内容发生变化，则在调用该组件时在onChangeType中重新传入表单信息和数据
        console.log(val,name);
        this.form[name] = val
        this.$emit("onChangeType",name,this.form[name])
    },
    customerChange(val,name){
      this.form[name]=val
      this.$emit("onChangeType",name,val)
    },
    //通用下拉select组件返回函数onSelect，表单name统一绑定列表pid, onChangeType会返回name和选中记录val
    //val包含选中记录的pid和记录全部信息：val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    //例如： { label: '供应商名称', name: 'supplierOrgPid', type: 'supplier', placeholder: '请选择供应商名称' },
    onSelect(val,name){
      console.log(val,name);
      this.form[name]=val[0]
      this.$emit("onChangeType",name,val)
    },
    salegoodsChange (val,name) {
      // console.log(name);
        this.form[name] = val
        this.$emit("onChangeType",name,this.form[name])
    },
    imgUploaded(imgurl,name){
      this.form[name] = imgurl
      this.$emit("onChangeType",name, imgurl)
      console.log(imgurl);
    },
    imgsUploaded(imgurl,name){
      this.form[name] = imgurl
      this.$emit("onChangeType",name, imgurl)
      console.log(imgurl);
    },
    // 单位选择Change
    orgChange (val, name) {
      console.log(val)
      console.log(name)
      this.form[name] = val
      this.$emit("onChangeType",name,this.form[name])
    },
    orgOnsearch(val1,  name) {
      console.log(val1)
      console.log(name)
      this.$emit("orgsearch",name, val1)
    },
    addInfo(){ //点击表单中的添加
      console.log(this.form);
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let submitdata=JSON.parse(JSON.stringify(this.form))
          for (let key in submitdata) {
            for (let keys in this.forms) {
              if (key==keys) {
                submitdata[key]=this.forms[keys]
              }
            }
          }
          console.log('查询中',submitdata);
          this.$emit('onAddInfo',submitdata)
        } else {
          console.log('信息不完整!!');
          return false;
        }
      });
    },
    // 确定
    submitForm(formName) {
      console.log(this.form);
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let submitdata=JSON.parse(JSON.stringify(this.form))
          for (let key in submitdata) {
            for (let keys in this.forms) {
              if (key==keys) {
                submitdata[key]=this.forms[keys]
              }
            }
          }
          console.log('查询中',submitdata);
          this.$emit('onSubmit',submitdata)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      
    },
    // 重置
    resetForm(formName) {
      this.forms={}
      // this.$refs[formName].resetFields();
      this.form= JSON.parse(JSON.stringify(this.resetobj))
      // console.log("重置表单后",this.form);
      this.$emit("closeModal")
    },
    cancel(){
      this.$emit("onCancel")
    }
    
  }
}
</script>

<style scoped>
.formalert{
  margin: auto;
  width: 800px;
}
.formBox{
  padding-left: 5px;
  /* max-height:calc( 70vh - 40px ); */
  overflow-y: scroll;
}
.formBtn{
  height: 7vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items:center;
  /* border: 1px solid #eee; */
}
.formRow{
  min-height: 50px;
  /* border: 1px solid #000; */
  
}
.inline{
  float: left;
  width: 47%;
  min-height: 60px;
  margin-right: 1%;
}
.ant-form-item {
  margin:0;
  /* border: 1px solid #e02; */
}
.btn{
  margin-left: 20px;
}
.labels{
  width: 100%;
  line-height: 40px;
  text-align: right;
}
.btnFixed{
  width: 100%;
  line-height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.btnInForm{
  margin-left: 70%;
}

</style>

//用法:formInfos的name和formDatas的属性一定要按照顺序一一对应
// <search-layout :formInfos="formInfos" :formDatas="formDatas"></search-layout>
// formInfos:[
// {label:'平台订单号1',name:'oid',type:'input',placeholder:'请输入'},
// {label:'省',name:'adress1',type:'select',placeholder:'请选择',options:[{id:'0',value:'所有'},{id:'1',value:'四川'},{id:'2',value:'陕西'}],link:'1'},
// {label:'市',name:'adress2',type:'select',placeholder:'请选择',options:[{id:'0',value:'所有'},{id:'1',value:'成都'},{id:'2',value:'泸州'}],link:'2'},
// {label:'创建日期',name:'timeFrom',type:'datatime',placeholder:'请选择日期',},
// {label:'到',name:'timeTo',type:'datatime',placeholder:'请选择日期',},
// {label:'a3',name:'name',type:'input',placeholder:'请输入',},
// {label:'a2',name:'select1',type:'select',placeholder:'请选择',options:[{id:'0',value:'所有'},{id:'1',value:'a'},{id:'2',value:'b'}],link:'2'},
// {label:'查询',name:'btn',type:'btn',},
// ],
// formDatas:{
// oid:'12315',
// adress1:'1',
// adress2:'',
// timeFrom:null,
// timeTo:null,
// name:'',
// select1:''
// }